<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 表格数据加载状态
const tableLoading = ref(false);

// 团购券列表数据
const voucherList = ref([]);

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  dateRange: []
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 团购券状态选项
const voucherStatusOptions = [
  { label: '未使用', value: 'unused' },
  { label: '已使用', value: 'used' },
  { label: '已过期', value: 'expired' },
  { label: '已退款', value: 'refunded' },
  { label: '已作废', value: 'invalid' }
];

// 加载团购券数据
const loadVoucherData = () => {
  tableLoading.value = true;
  
  // 模拟API请求
  setTimeout(() => {
    // 生成模拟数据
    voucherList.value = Array.from({ length: 20 }, (_, index) => {
      const id = 'VCH' + (100000 + index).toString();
      const statusIndex = Math.floor(Math.random() * 5);
      const now = new Date();
      
      // 随机生成购买和过期日期
      const buyDate = new Date(now.getTime() - Math.floor(Math.random() * 90) * 24 * 60 * 60 * 1000);
      const expireDate = new Date(buyDate.getTime() + 180 * 24 * 60 * 60 * 1000); // 有效期6个月
      
      // 使用日期（如果已使用）
      let useDate = null;
      if (voucherStatusOptions[statusIndex].value === 'used') {
        useDate = new Date(buyDate.getTime() + Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000);
      }
      
      // 随机金额
      const price = Math.floor(Math.random() * 200) + 50;
      const originalPrice = price + Math.floor(Math.random() * 100);
      
      // 随机会员信息
      const memberName = `会员${Math.floor(Math.random() * 100) + 1}`;
      const memberPhone = `1381234${(Math.floor(Math.random() * 10000)).toString().padStart(4, '0')}`;
      
      // 团购券名称
      const voucherNames = [
        '棋牌2小时畅玩券',
        '麻将包房3小时券',
        '德州扑克特惠券',
        '棋牌全天畅玩券',
        '茶水套餐券',
        'VIP包房体验券'
      ];
      const voucherName = voucherNames[Math.floor(Math.random() * voucherNames.length)];
      
      return {
        id,
        voucherNo: id,
        voucherName,
        memberName,
        memberPhone,
        price: price.toFixed(2),
        originalPrice: originalPrice.toFixed(2),
        buyDate: buyDate.toLocaleDateString(),
        expireDate: expireDate.toLocaleDateString(),
        useDate: useDate ? useDate.toLocaleDateString() : '--',
        status: voucherStatusOptions[statusIndex].value,
        statusName: voucherStatusOptions[statusIndex].label,
        verifyCode: Math.floor(Math.random() * 900000) + 100000, // 6位验证码
        verifyOperator: voucherStatusOptions[statusIndex].value === 'used' ? '操作员' + Math.floor(Math.random() * 5 + 1) : '--'
      };
    });
    
    pagination.total = 156; // 模拟总数据量
    tableLoading.value = false;
  }, 1000);
};

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadVoucherData();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadVoucherData();
};

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1;
  loadVoucherData();
};

// 重置查询条件
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.status = '';
  searchForm.dateRange = [];
  
  pagination.currentPage = 1;
  loadVoucherData();
};

// 查看团购券详情
const viewVoucherDetails = (row) => {
  ElMessage.info(`查看团购券详情：${row.voucherNo}`);
};

// 验证团购券
const verifyVoucher = (row) => {
  if (row.status !== 'unused') {
    ElMessage.warning('只能验证未使用的团购券');
    return;
  }
  
  ElMessageBox.confirm(`确定要验证团购券"${row.voucherNo}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('验证成功');
    row.status = 'used';
    row.statusName = '已使用';
    row.useDate = new Date().toLocaleDateString();
    row.verifyOperator = '当前操作员';
  }).catch(() => {});
};

// 退款操作
const refundVoucher = (row) => {
  if (row.status !== 'unused') {
    ElMessage.warning('只能对未使用的团购券进行退款');
    return;
  }
  
  ElMessageBox.confirm(`确定要退款团购券"${row.voucherNo}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('退款成功');
    row.status = 'refunded';
    row.statusName = '已退款';
  }).catch(() => {});
};

// 作废操作
const invalidateVoucher = (row) => {
  if (row.status !== 'unused') {
    ElMessage.warning('只能作废未使用的团购券');
    return;
  }
  
  ElMessageBox.confirm(`确定要作废团购券"${row.voucherNo}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('作废成功');
    row.status = 'invalid';
    row.statusName = '已作废';
  }).catch(() => {});
};

// 创建团购券活动
const createVoucherActivity = () => {
  ElMessage.info('打开创建团购券活动表单');
};

// 导出团购券
const exportVouchers = () => {
  ElMessage.success('团购券数据导出成功');
};

// 初始化加载
onMounted(() => {
  loadVoucherData();
});
</script>

<template>
  <div class="voucher-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>团购券管理</h2>
    </div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="团购券号/名称/会员姓名/手机号"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option 
              v-for="item in voucherStatusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="购买日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 表格区域 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>团购券列表</span>
          <div>
            <el-button type="primary" @click="createVoucherActivity">
              <el-icon><Plus /></el-icon>
              创建团购活动
            </el-button>
            <el-button type="success" @click="exportVouchers">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="voucherList" 
        v-loading="tableLoading" 
        border 
        style="width: 100%"
      >
        <el-table-column prop="voucherNo" label="团购券号" width="110" />
        <el-table-column prop="voucherName" label="团购券名称" width="150" />
        <el-table-column prop="memberName" label="购买会员" width="100" />
        <el-table-column prop="memberPhone" label="手机号" width="120" />
        <el-table-column label="优惠价/原价" width="120">
          <template #default="{ row }">
            <div>¥{{ row.price }}</div>
            <div class="original-price">¥{{ row.originalPrice }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="buyDate" label="购买日期" width="100" />
        <el-table-column prop="expireDate" label="过期日期" width="100" />
        <el-table-column prop="useDate" label="使用日期" width="100" />
        <el-table-column prop="verifyCode" label="验证码" width="100" />
        <el-table-column prop="status" label="状态" width="90">
          <template #default="{ row }">
            <el-tag 
              :type="
                row.status === 'unused' ? 'primary' : 
                row.status === 'used' ? 'success' : 
                row.status === 'expired' ? 'warning' : 
                row.status === 'refunded' ? 'info' : 'danger'
              "
            >
              {{ row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="240">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="viewVoucherDetails(row)"
            >
              详情
            </el-button>
            <el-button 
              v-if="row.status === 'unused'"
              size="small" 
              type="success" 
              @click="verifyVoucher(row)"
            >
              验证
            </el-button>
            <el-button 
              v-if="row.status === 'unused'"
              size="small" 
              type="primary" 
              @click="refundVoucher(row)"
            >
              退款
            </el-button>
            <el-button 
              v-if="row.status === 'unused'"
              size="small" 
              type="danger" 
              @click="invalidateVoucher(row)"
            >
              作废
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 团购券数据统计 -->
    <el-row :gutter="20" class="stat-row">
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">团购券总数</div>
          <div class="stat-value">2,356</div>
          <div class="stat-info">
            <el-tag type="primary">未使用: 896</el-tag>
            <el-tag type="success">已使用: 1,230</el-tag>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">本月销售额</div>
          <div class="stat-value">¥16,320</div>
          <div class="stat-info">
            <div class="stat-subinfo">环比增长 <span class="stat-up">+12%</span></div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">使用率</div>
          <div class="stat-value">58.9%</div>
          <div class="stat-info">
            <div class="stat-subinfo">过期率 <span class="stat-down">5.2%</span></div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">退款率</div>
          <div class="stat-value">3.7%</div>
          <div class="stat-info">
            <div class="stat-subinfo">退款金额 <span>¥4,580</span></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.voucher-container {
  padding: 20px;
}
.page-header {
  margin-bottom: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.stat-row {
  margin-top: 20px;
}
.stat-card {
  text-align: center;
  padding: 10px;
  height: 100%;
}
.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}
.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}
.stat-info {
  display: flex;
  justify-content: center;
  gap: 10px;
  flex-wrap: wrap;
}
.stat-subinfo {
  font-size: 13px;
  color: #606266;
}
.stat-up {
  color: #67C23A;
}
.stat-down {
  color: #F56C6C;
}
</style> 
